package com.snapan.controller;

import com.snapan.entity.EmailVerification;
import com.snapan.service.VerificationCodeService;
import com.snapan.vo.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/verification")
public class VerificationCodeController {

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 发送验证码
     * @param email 邮箱地址
     * @param type 验证码类型：1-注册，2-重置密码
     */
    @PostMapping("/send")
    public BaseResponse sendVerificationCode(
            @RequestParam String email,
            @RequestParam Byte type) {

        // 验证参数
        if (email == null || email.trim().isEmpty()) {
            return BaseResponse.error("邮箱地址不能为空");
        }

        if (type == null || (type != 1 && type != 2)) {
            return BaseResponse.error("验证码类型错误");
        }

        // 检查发送频率
        if (verificationCodeService.isTooFrequent(email, type)) {
            return BaseResponse.error("请求过于频繁，请1分钟后再试");
        }

        // 生成并发送验证码
        boolean result = verificationCodeService.generateAndSendCode(email, type);

        return result ? BaseResponse.success("验证码发送成功") :
                BaseResponse.error("验证码发送失败");
    }

    /**
     * 验证验证码
     * @param email 邮箱地址
     * @param code 用户输入的验证码
     * @param type 验证码类型
     */
    @PostMapping("/verify")
    public BaseResponse verifyCode(
            @RequestParam String email,
            @RequestParam String code,
            @RequestParam Byte type) {

        // 验证参数
        if (email == null || email.trim().isEmpty()) {
            return BaseResponse.error("邮箱地址不能为空");
        }

        if (code == null || code.trim().isEmpty()) {
            return BaseResponse.error("验证码不能为空");
        }

        if (type == null || (type != 1 && type != 2)) {
            return BaseResponse.error("验证码类型错误");
        }

        boolean isValid = verificationCodeService.verifyCode(email, code, type);

        return isValid ? BaseResponse.success("验证成功") :
                BaseResponse.error("验证码错误或已过期");
    }
}